import store from '@/store';
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 使用循环的方式判断一个元素是否存在于一个数组中
 * @param {Object} arr 数组
 * @param {Object} value 元素值
 */
export function isInMenu(arr, value) {
  for (var i = 0; i < arr.length; i++) {
    if (value === arr[i].code) {
      return true;
    }
  }
  return false;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 */
export function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    var menu = store.getters.menu
    if (menu) {
      if (tmp.meta) {
        if (isInMenu(menu, tmp.meta.code)) {
          if (tmp.children) {
            tmp.children = filterAsyncRoutes(tmp.children)
          }
          res.push(tmp)
        }
      } else {
        res.push(tmp)
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
